package page.ineffable.photostorage.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import page.ineffable.photostorage.pojo.Photo;
import page.ineffable.photostorage.service.PhotoService;
import page.ineffable.photostorage.util.ReturnCode;
import page.ineffable.photostorage.util.StringUtils;
import page.ineffable.photostorage.util.WaterMarkUtils;

import javax.servlet.http.HttpSession;

/**
 * 图片controller
 *
 * @author lqs2
 * @date 2018/10/29, Mon
 */
@Controller
@RequestMapping("/image")
@Transactional(rollbackFor = Exception.class)
public class ImageController {

    private final PhotoService photoService;
    private static ObjectMapper objectMapper = new ObjectMapper();
    private static Logger log = LoggerFactory.getLogger(ImageController.class);


    @Autowired
    public ImageController(PhotoService photoService) {
        this.photoService = photoService;
    }

    /**
     * 文件上传
     *
     * @param file     文件
     * @param filename 文件名
     **/
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file, @RequestParam String filename, HttpSession session) {
        String username = (String) session.getAttribute("un");
        if (!StringUtils.isEmpty(username)) {
            Photo photo = photoService.uploadPhoto(username, filename, file);
            try {
                return photo != null ? objectMapper.writeValueAsString(photo) : ReturnCode.SERVICE_FAILED;
            } catch (JsonProcessingException e) {
                log.error("", e);
            }
            return ReturnCode.SERVICE_FAILED;
        }
        return ReturnCode.SESSION_INVALID;
    }

    /**
     * 显示用户所有的图片
     *
     * @param session 当前会话
     **/
    @GetMapping("/display")
    @ResponseBody
    public String displayPhotos(HttpSession session) {
        String username = (String) session.getAttribute("un");
        if (!StringUtils.isEmpty(username)) {
            try {
                return objectMapper.writeValueAsString(photoService.getPhotos(username));
            } catch (JsonProcessingException e) {
                log.error("", e);
            }
            return ReturnCode.SERVICE_ERROR;
        }
        return ReturnCode.SESSION_INVALID;
    }

    /**
     * 根据图像id删除图像
     *
     * @param id      图像id
     * @param session 当前会话
     **/
    @GetMapping("/drop")
    @ResponseBody
    public String dropPhoto(String id, HttpSession session) {
        String username = (String) session.getAttribute("un");
        if (!StringUtils.isEmpty(username)) {
            return photoService.dropPhoto(id, username) ? ReturnCode.SERVICE_OK : ReturnCode.SERVICE_FAILED;
        }
        return ReturnCode.SESSION_INVALID;
    }

    /**
     * 用户选择给图片添加水印
     *
     * @param id      图像的id
     * @param text    水印的内容
     * @param loc     添加水印的位置
     * @param col     添加水印的颜色
     * @param plain   是否正常的字体，否则斜体
     * @param session 当前会话
     **/
    @PostMapping("/addWaterMark")
    @ResponseBody
    public String addWaterMark(String id, String text, int loc, int col, boolean plain, HttpSession session) {
        String username = (String) session.getAttribute("un");
        if (!StringUtils.isEmpty(username)) {
            Photo photo = photoService.getPhotoById(id);
            if (photo != null) {
                boolean b1 = WaterMarkUtils.addWaterMark(photo, text, loc, col, plain, photoService.getImageRootPath());
                if (b1) {
                    photo.setHasWaterMark(true);
                    boolean b2 = photoService.modImageInfo(id, photo);
                    if (b2) {
                        try {
                            return objectMapper.writeValueAsString(photo);
                        } catch (JsonProcessingException e) {
                            log.error("", e);
                        }
                    }
                }
            }
            return ReturnCode.SERVICE_FAILED;
        }
        return ReturnCode.SESSION_INVALID;
    }

    /**
     * 用户重置图像（去除水印）
     *
     * @param id      图像id
     * @param session 会话
     **/
    @GetMapping("/reset")
    @ResponseBody
    public String resetPhoto(String id, HttpSession session) {
        String username = (String) session.getAttribute("un");
        if (!StringUtils.isEmpty(username)) {
            Photo photo = photoService.getPhotoById(id);
            if (photo != null && photo.getAuthor().equals(username) && photoService.modImageMarkState(id, 0)) {
                photo.setHasWaterMark(false);
                try {
                    return objectMapper.writeValueAsString(photo);
                } catch (JsonProcessingException e) {
                    log.error("", e);
                }
            }
            return ReturnCode.SERVICE_FAILED;
        }
        return ReturnCode.SESSION_INVALID;
    }
}
